package com.edu.backend.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yanjunfeng
 * @Description: TODO
 * @Date: Created in 上午10:32 2023/6/20
 * @Modified By:
 */

@Slf4j
@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 设置支持cookie跨域
        corsConfiguration.setAllowCredentials(true);

        // 设置允许哪些域访问
        List<String> allowOrigins = new ArrayList<>();
        allowOrigins.add("*");

        // 注意 ！！！！  将setAllowedOrigin 改为 setAllowedOriginPatterns
        // corsConfiguration.setAllowedOrigin(allowOrigins);
        corsConfiguration.setAllowedOriginPatterns(allowOrigins);

        // 设置允许的头
        List<String> allowHeaders = new ArrayList<>();
        allowHeaders.add("*");
        corsConfiguration.setAllowedHeaders(allowHeaders);

        // 设置允许的请求方式
        List<String> allowMethod = new ArrayList<>();
        allowMethod.add("GET");
        allowMethod.add("POST");
        allowMethod.add("PUT");
        allowMethod.add("PATCH");
        allowMethod.add("DELETE");
        corsConfiguration.setAllowedMethods(allowMethod);

        //corsConfiguration.setMaxAge(ALLOW_TIME);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}
